package util

import (
	"github.com/dgrijalva/jwt-go"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/setting"
)

var jwtSecret = []byte(setting.JwtSecret)

type Claims struct {
	UserId string `json:"userId"`
	jwt.StandardClaims
}

func GenerateToken(userId string) (string, error) {
	claims := Claims{
		userId,
		jwt.StandardClaims{
			ExpiresAt: 0,
			Issuer:    "k-develop",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(jwtSecret)

	return token, err
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(
		token, &Claims{},
		func(token *jwt.Token) (interface{}, error) {
			return jwtSecret, nil
		},
	)

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
